package com.blog.oguzhan.soapui.utils.ibmltpa2token;


import java.io.InputStream;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.protocol.Protocol;

public class TokenCreator {
	
	private String username;
	private String password;
	private String host;
	private int port;
	private static final String URI = "/ibm/console/j_security_check";

	public TokenCreator(String username, String password, String url) throws Exception {
		this(new EnvironmentConfig(null, url, username, password));
	}
	
	public TokenCreator(String username, String password, String host, int port) {
		this.username = username;
		this.password = password;
		this.host = host;
		this.port = port;
	}

	public TokenCreator(EnvironmentConfig environmentConfig) throws Exception {
		this.username = environmentConfig.getUser();
		this.password = environmentConfig.getPassword();
		String url = environmentConfig.getUrl();
		if (url.startsWith("https://")) {
			url = url.substring(8);
			String hostAndPort = url.split("/")[0];
			this.host = hostAndPort.split(":")[0];
			this.port = Integer.valueOf(hostAndPort.split(":")[1]);
		}
		else {
			throw new Exception("APPLICATION SERVER URL MUST STARTS WITH 'https://'");
		}
	}

	@SuppressWarnings({ "deprecation", "unused" })
	public String create() {

		Protocol myhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), this.port);
		HttpClient client = new HttpClient();
		client.getHostConfiguration().setHost(this.host, this.port, myhttps);
		InputStream responseStream = null;
		int statusCode=0;
		PostMethod method = new PostMethod(URI);
		method.addParameter("j_username", this.username);
		method.addParameter("j_password", this.password);
		try {
			statusCode = client.executeMethod(method);
		    
			System.out.println("HTTP CODE: " + statusCode);
//			response = method.getResponseBody();
//			responseStream = method.getResponseBodyAsStream();
			Header[] headerArray = method.getResponseHeaders();
			for (int i = 0; i < headerArray.length; ++i) {
				Header header = headerArray[i];
				String headerValue = header.getValue();
				int minLength = new String("LtpaToken=").length();
				int commaOffset = headerValue.indexOf(';');
				if ((headerValue.startsWith("LtpaToken=")) && (headerValue.length() > minLength)) {
					return headerValue.substring(minLength, commaOffset);
//					System.out.println(token);
//
//					StringSelection data = new StringSelection(token);
//					Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
//					clipboard.setContents(data, data);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			method.releaseConnection();
//		    method.recycle( );
		}
		
		return "";
	}
}